package org.dy.servlet.listener;

import java.util.Vector;

import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;

public class OnlineLoginCount implements HttpSessionBindingListener {
	public OnlineLoginCount() {
	}

	private Vector<String> users = new  Vector<String>();

	public int getCount() {
		users.trimToSize();
		return users.capacity();
	}

	public boolean existUser(String userName) {
		users.trimToSize();
		boolean existUser = false;
		for (int i = 0; i < users.capacity(); i++) {
			if (userName.equals((String) users.get(i))) {
				existUser = true;
				break;
			}
		}
		return existUser;
	}

	public boolean deleteUser(String userName) {
		users.trimToSize();
		if (existUser(userName)) {
			int currUserIndex = -1;
			for (int i = 0; i < users.capacity(); i++) {
				if (userName.equals((String) users.get(i))) {
					currUserIndex = i;
					break;
				}
			}
			if (currUserIndex != -1) {
				users.remove(currUserIndex);
				users.trimToSize();
				return true;
			}
		}
		return false;
	}

	public Vector getOnLineUser() {
		return users;
	}

	public void valueBound(HttpSessionBindingEvent e) {
		users.trimToSize();
		if (!existUser(e.getName())) {
			users.add(e.getName());
		} else {

		}
	}

	public void valueUnbound(HttpSessionBindingEvent e) {
		users.trimToSize();
		String userName = e.getName();
		deleteUser(userName);
	}
}
